<?php

/*
 * 发货流程
 */

namespace app\seller\controller;

class Deliver extends \app\common\controller\Seller
{

    /**
     * 发货列表
     *
     */
    public function index()
    {
        $model_order = model('Common/Order');
        $state = input('state');
        if (!in_array($state, array('deliverno', 'delivering', 'delivered'))) {
            $state = 'deliverno';
        }
        $order_state = str_replace(array('deliverno', 'delivering', 'delivered'), array(ORDER_STATE_PAY, ORDER_STATE_SEND, ORDER_STATE_SUCCESS), $state);
        $condition = array();
        $condition['store_id'] = $this->store_id;
        $condition['order_state'] = $order_state;
        
        $buyer_name = input('buyer_name');
        if ($buyer_name != '') {
            $condition['buyer_name'] = $buyer_name;
        }
        
        $order_sn = input('order_sn');
        if ($order_sn != '') {
            $condition['order_sn'] = $order_sn;
        }
        
        $query_date = $this->query_date();
        if ($query_date && is_array($query_date)) {
            $condition['add_time'] = $query_date;
        }
        
        $order_list = $model_order->getOrderList($condition, 5, '*', 'order_id desc', '', array('order_goods', 'order_common', 'member'));
        foreach ($order_list as $key => $order_info) {
            foreach ($order_info['extend_order_goods'] as $value) {
                $value['image_60_url']  = img_url($value['goods_image'], 60);
                $value['image_240_url'] = img_url($value['goods_image'], 240);
                $value['goods_type_cn'] = orderGoodsType($value['goods_type']);
                $value['goods_url'] = url('index/goods/detail', array('goods_id' => $value['goods_id']));
                if ($value['goods_type'] == 5) {
                    $order_info['zengpin_list'][] = $value;
                } else {
                    $order_info['goods_list'][] = $value;
                }
            }

            if (empty($order_info['zengpin_list'])) {
                $order_info['goods_count'] = count($order_info['goods_list']);
            } else {
                $order_info['goods_count'] = count($order_info['goods_list']) + 1;
            }
            $order_list[$key] = $order_info;
        }
        $this->assign('order_list', $order_list);
        //$this->assign('show_page', $model_order->showpage());
        $this->profile_menu('deliver', $state);
        return $this->fetch();
    }

    /**
     * 发货
     */
    public function send()
    {
        $order_id = input('order_id/d');
        if ($order_id <= 0) {
            return $this->error('参数错误');
        }

        $model_order = model('Common/Order');
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['store_id'] = $this->store_id;
        $order_info = $model_order->getOrderInfo($condition, array('order_common', 'order_goods'));
        
        //如果是线下付款，查询到平台还没有确认核对收款，商家无法进入发货环节。
        //已确认付款则进入正常发货流程
        if (intval($order_info['order_state']) != 20) {
            return $this->error('平台未确认账单，无法进行发货设置');
        }
        
        $if_allow_send = intval($order_info['lock_state']) || !in_array($order_info['order_state'], array(ORDER_STATE_PAY, ORDER_STATE_SEND));
        if ($if_allow_send) {
            return $this->error('权限不足');
        }

        if ($this->request->isPost()) {
            $logic_order = model('Common/Order', 'logic');
            $data = input('post.');
            $data['reciver_info'] = $this->_get_reciver_info();
            $data['store_id'] = $this->store_id;
            $result = $logic_order->changeOrderSend($order_info, 'seller', $this->member_info['name'], $data);
            if (!$result['status']) {
                return $this->error($result['msg']);
            } else {
                return showDialog($result['msg'], input('post.ref_url'), 'succ');
            }
        }

        $this->assign('order_info', $order_info);
        //取发货地址
        $model_daddress = model('Common/Daddress');
        if ($order_info['extend_order_common']['daddress_id'] > 0) {
            $daddress_info = $model_daddress->getAddressInfo(array('address_id' => $order_info['extend_order_common']['daddress_id']));
        } else {
            //取默认地址
            $daddress_info = $model_daddress->getAddressList(array('store_id' => $_SESSION['store_id']), '*', 'is_default desc', 1);
            $daddress_info = $daddress_info[0];

            //写入发货地址编号
            $this->_edit_order_daddress($daddress_info['address_id'], $order_id);
        }
        $this->assign('daddress_info', $daddress_info);

        $express_list = \Express::lists();

        //如果是自提订单，只保留自提快递公司
        if (!empty($order_info['extend_order_common']['reciver_info']['dlyp'])) {
            foreach ($express_list as $k => $v) {
                if ($v['e_zt_state'] == '0')
                    unset($express_list[$k]);
            }
            $my_express_list = array_keys($express_list);
        } else {
            //快递公司
            $my_express_list = model('Common/Store')->getExtend($this->store_id, 'express');
            if (!empty($my_express_list)) {
                $my_express_list = explode(',', $my_express_list);
            }
        }

        $this->assign('my_express_list', $my_express_list);
        $this->assign('express_list', $express_list);
        $this->assign('left_nav', 'deliver');
        return $this->fetch();
    }

    /**
     * 编辑收货地址
     * @return boolean
     */
    public function buyer_address_edit()
    {
        $order_id = input('order_id/d');
        if ($order_id <= 0) {
            return false;
        }
        $model_order = model('Common/Order');
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['store_id'] = $this->store_id;
        $order_common_info = $model_order->getOrderCommonInfo($condition);
        if (!$order_common_info) {
            return false;
        }
        $order_common_info['reciver_info'] = @unserialize($order_common_info['reciver_info']);
        $this->assign('address_info', $order_common_info);

        return $this->fetch();
    }

    /**
     * 收货地址保存
     */
    public function buyer_address_save()
    {
        $model_order = model('Common/Order');
        $data = array();
        $data['reciver_name'] = input('post.reciver_name');
        $data['reciver_info'] = $this->_get_reciver_info();
        $condition = array();
        $condition['order_id'] = input('post.order_id/d');
        $condition['store_id'] = $this->store_id;
        $result = $model_order->editOrderCommon($data, $condition);
        if ($result) {
            return 'true';
        } else {
            return 'flase';
        }
    }

    /**
     * 组合reciver_info
     */
    private function _get_reciver_info()
    {
        $reciver_info = array(
            'address' => input('post.reciver_area') . ' ' . input('post.reciver_street'),
            'phone' => trim(input('post.reciver_mob_phone') . ',' . input('post.reciver_tel_phone'), ','),
            'area' => input('post.reciver_area'),
            'street' => input('post.reciver_street'),
            'mob_phone' => input('post.reciver_mob_phone'),
            'tel_phone' => input('post.reciver_tel_phone'),
            'dlyp' => input('post.reciver_dlyp')
        );
        return serialize($reciver_info);
    }

    /**
     * 选择发货地址
     * @return boolean
     */
    public function send_address_select()
    {
        $address_list = model('Common/Daddress')->getAddressList(array('store_id' => $this->store_id));
        $this->assign('address_list', $address_list);
        $this->assign('order_id', input('order_id/d'));
        return $this->fetch();
    }

    /**
     * 保存发货地址修改
     */
    public function send_address_save()
    {
        $result = $this->_edit_order_daddress(input('post.daddress_id'), input('post.order_id/d'));
        if ($result) {
            return 'true';
        } else {
            return 'flase';
        }
    }

    /**
     * 修改发货地址
     */
    private function _edit_order_daddress($daddress_id, $order_id)
    {
        $model_order = model('Common/Order');
        $data = array();
        $data['daddress_id'] = intval($daddress_id);
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['store_id'] = $this->store_id;
        return $model_order->editOrderCommon($data, $condition);
    }

    /**
     * 物流跟踪
     */
    public function search_deliver()
    {
        $order_sn = input('order_sn');
        if (!is_numeric($order_sn)) {
            return $this->error('参数错误');
        }
        
        $model_order = model('Common/Order');
        $condition['order_sn'] = $order_sn;
        $condition['store_id'] = $this->store_id;
        $order_info = $model_order->getOrderInfo($condition, array('order_common', 'order_goods'));
        if (empty($order_info) || $order_info['shipping_code'] == '') {
            return $this->error('未找到信息');
        }
        $order_info['state_info'] = orderState($order_info);
        $this->assign('order_info', $order_info);
        //卖家发货信息
        $daddress_info = model('Common/Daddress')->getAddressInfo(array('address_id' => $order_info['extend_order_common']['daddress_id']));
        $this->assign('daddress_info', $daddress_info);

        //取得配送公司代码
        $express = \Express::lists();
        $this->assign('e_code', $express[$order_info['extend_order_common']['shipping_express_id']]['e_code']);
        $this->assign('e_name', $express[$order_info['extend_order_common']['shipping_express_id']]['e_name']);
        $this->assign('e_url', $express[$order_info['extend_order_common']['shipping_express_id']]['e_url']);
        $this->assign('shipping_code', $order_info['shipping_code']);

        $this->profile_menu('search', 'search');
        return $this->fetch('detail');
    }

    /**
     * 延迟收货
     */
    public function delay_receive()
    {
        $order_id = input('order_id/d');
        $model_trade = model('Common/Trade');
        $model_order = model('Common/Order');
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['store_id'] = $this->store_id;
        $condition['lock_state'] = 0;
        $order_info = $model_order->getOrderInfo($condition);

        //取目前系统最晚收货时间
        $delay_time = $order_info['delay_time'] + ORDER_AUTO_RECEIVE_DAY * 3600 * 24;
        if ($this->request->isPost()) {
            $delay_date = input('delay_date/d');
            if (!in_array($delay_date, array(5, 10, 15))) {
                return showDialog('参数错误', '', 'error', !$this->request->isAjax() ? '' : 'CUR_DIALOG.close();');
            }
            $update = $model_order->editOrder(array('delay_time' => array('exp', 'delay_time+' . $delay_date * 3600 * 24)), $condition);
            if ($update) {
                //新的最晚收货时间
                $dalay_date = date('Y-m-d H:i:s', $delay_time + $delay_date * 3600 * 24);
                return showDialog("成功将最晚收货期限延迟到了" . $dalay_date . '&emsp;', '', 'succ', !$this->request->isAjax() ? '' : 'CUR_DIALOG.close();', 4);
            } else {
                return showDialog('延迟失败', '', 'succ', !$this->request->isAjax() ? '' : 'CUR_DIALOG.close();');
            }
        } else {
            $order_info['delay_time'] = $delay_time;
            $this->assign('order_info', $order_info);
            return $this->fetch();
        }
    }

    /**
     * 从第三方取快递信息
     *
     */
    public function get_express()
    {
        exit(json_encode(false));
        $url = 'http://www.kuaidi100.com/query?type=' . $_GET['e_code'] . '&postid=' . $_GET['shipping_code'] . '&id=1&valicode=&temp=' . random(4) . '&sessionid=&tmp=' . random(4);
        import('function.ftp');
        $content = dfsockopen($url);
        $content = json_decode($content, true);
        if ($content['status'] != 200)
            exit(json_encode(false));
        $content['data'] = array_reverse($content['data']);
        $output = '';
        if (is_array($content['data'])) {
            foreach ($content['data'] as $k => $v) {
                if ($v['time'] == '')
                    continue;
                $output .= '<li>' . $v['time'] . '&nbsp;&nbsp;' . $v['context'] . '</li>';
            }
        }
        if ($output == '')
            exit(json_encode(false));
        echo json_encode($output);
    }

    /**
     * 运单打印
     */
    public function waybill_print()
    {
        $order_id = input('order_id/d');
        if ($order_id <= 0) {
            return $this->error('参数错误');
        }

        $model_order = model('Common/Order');
        $model_store_waybill = model('Common/StoreWaybill');
        $model_waybill = model('Common/Waybill');

        $order_info = $model_order->getOrderInfo(array('order_id' => $order_id), array('order_common'));

        $store_waybill_list = $model_store_waybill->getStoreWaybillList(array('store_id' => $order_info['store_id']), 'is_default desc');

        $store_waybill_info = $this->_getCurrentWaybill($store_waybill_list, input('store_waybill_id'));
        if (empty($store_waybill_info)) {
            $this->error('请首先绑定打印模板', url('store/waybill/manage'));
        }

        $waybill_info = $model_waybill->getWaybillInfo(array('waybill_id' => $store_waybill_info['waybill_id']));
        if (empty($waybill_info)) {
            $this->error('请首先绑定打印模板', url('store/waybill/manage'));
        }

        //根据订单内容获取打印数据
        $print_info = $model_waybill->getPrintInfoByOrderInfo($order_info);

        //整理打印模板
        $store_waybill_data = unserialize($store_waybill_info['store_waybill_data']);
        foreach ($waybill_info['waybill_data'] as $key => $value) {
            $waybill_info['waybill_data'][$key]['show'] = $store_waybill_data[$key]['show'];
            $waybill_info['waybill_data'][$key]['content'] = $print_info[$key];
        }

        //使用商家自定义的偏移尺寸
        $waybill_info['waybill_pixel_top'] = $store_waybill_info['waybill_pixel_top'];
        $waybill_info['waybill_pixel_left'] = $store_waybill_info['waybill_pixel_left'];

        $this->assign('waybill_info', $waybill_info);
        $this->assign('store_waybill_list', $store_waybill_list);
        return $this->fetch('waybill/waybill_print');
    }

    /**
     * 获取当前打印模板
     */
    private function _getCurrentWaybill($store_waybill_list, $store_waybill_id)
    {
        if (empty($store_waybill_list)) {
            return false;
        }

        $store_waybill_id = intval($store_waybill_id);

        $store_waybill_info = null;

        //如果指定模板使用指定的模板，未指定使用默认模板
        if ($store_waybill_id > 0) {
            foreach ($store_waybill_list as $key => $value) {
                if ($store_waybill_id == $value['store_waybill_id']) {
                    $store_waybill_info = $store_waybill_list[$key];
                    break;
                }
            }
        }

        if (empty($store_waybill_info)) {
            $store_waybill_info = $store_waybill_list[0];
        }

        return $store_waybill_info;
    }

    /**
     * 用户中心右边，小导航
     *
     * @param string	$menu_type	导航类型
     * @param string 	$menu_key	当前导航的menu_key
     * @return
     */
    private function profile_menu($menu_type, $menu_key = '')
    {
        $menu_array = array();
        switch ($menu_type) {
            case 'deliver':
                $menu_array = array(
                    array('menu_key' => 'deliverno', 'menu_name' => '待发货', 'menu_url' => url('seller/deliver/index?state=deliverno')),
                    array('menu_key' => 'delivering', 'menu_name' => '发货中', 'menu_url' => url('seller/deliver/index?state=delivering')),
                    array('menu_key' => 'delivered', 'menu_name' => '已发货', 'menu_url' => url('seller/deliver/index?state=delivered')),
                );
                break;
            case 'search':
                $menu_array = array(
                    1 => array('menu_key' => 'nodeliver', 'menu_name' => '待发货', 'menu_url' => url('seller/deliver/index?state=nodeliver')),
                    2 => array('menu_key' => 'delivering', 'menu_name' => '发货中', 'menu_url' => url('seller/deliver/index?state=delivering')),
                    3 => array('menu_key' => 'delivered', 'menu_name' => '已发货', 'menu_url' => url('seller/deliver/index?state=delivered')),
                    4 => array('menu_key' => 'search', 'menu_name' => '物流详情', 'menu_url' => '###'),
                );
                break;
        }
        $this->assign('member_menu', $menu_array);
        $this->assign('menu_key', $menu_key);
        $this->assign('left_nav', 'deliver');
    }

}
